/**
/**
 * JAVACC DEMO 1.0
 */

package freemarker.core;

import java.io.IOException;
import java.util.Iterator;

import freemarker.core.Environment;
import freemarker.core.Macro;
import freemarker.core.TemplateElement;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;

/**
 * description:  
 * @author Hou Dayu 创建时间：2016-7-28
 */
public class EnvironmentWrapper {

	Environment environment;

	public EnvironmentWrapper(Environment environment) {
		this.environment = environment;
	}

	void importMacros(Template template) throws TemplateModelException {
		Iterator it = template.getMacros().values().iterator();
		while (it.hasNext())
			visitMacroDef((Macro) it.next());
	}

	void visitMacroDef(Macro macro) throws TemplateModelException {
		TemplateModel templateModel = environment.getCurrentNamespace().get(macro.getName());

		if (templateModel == null)
			environment.visitMacroDef(macro);
	}

	public void include(Template includedTemplate) throws TemplateException, IOException {
		Template prevTemplate = environment.getTemplate();
		environment.setParent(includedTemplate);
		importMacros(includedTemplate);
		try {
			visit(includedTemplate.getRootTreeNode());
		} finally {
			environment.setParent(prevTemplate);
		}
	}

	void visit(TemplateElement element) throws TemplateException, IOException {
		if ((element instanceof Macro)) {
			MacroWrapper macroWrapper = new MacroWrapper((Macro) element);
			environment.visit(macroWrapper);
		} else if ((element instanceof MixedContent)) {
			MixedContentWrapper mixedContentWrapper = new MixedContentWrapper((MixedContent) element);
			environment.visit(mixedContentWrapper);
		} else {
			environment.visit(element);
		}
	}
}
